package com.kdtech.analyse.video;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.analyse.AnalyseNews;

/**
 * http://www.jlntv.cn/ 吉林网络广播电视台
 * @author 小聂 
 */
public class JlntvAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://www.jlntv.cn/.*folder[0-9]*/folder[0-9]*/[0-9]{4}-[0-9]{2}-[0-9]+/[0-9]+.html"				
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta video = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}		
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		video.setUrl(url);		
		String title = null;
		String desc = null;
		Long date = null;
		Document doc = Jsoup.parse(htmltxt);
		Elements select2 = doc.select("h1");
		if(select2!=null && select2.size()!=0){
			title = select2.get(0).text();
		}
		date = DateUtils.matchDate(url);
		video.setDate(date);
		video.setContent(desc);
		video.setTitle(title);
		video.setType(2);
		/**
		 * 解析用于更新的地址
		 */
		String updateUrl=null;
		Elements select = doc.select("script");
		if(select.size() > 0){
			Pattern clickReg = Pattern.compile("src=\".*\"");
			
			Matcher matcher_click = clickReg.matcher(select.get(4).toString());
			if (matcher_click.find()) {
				updateUrl = matcher_click.group();
				if(updateUrl != null){
					updateUrl = updateUrl.replace("src=", "");
					updateUrl = updateUrl.replace("\"", "").replace("&amp;", "&");
				}
				video.setUpdateUrl(updateUrl);
			}
		}
		if(updateUrl!=null){
			 video.setUpdateUrl(updateUrl);
			 NewsMeta update = Update(video);
			 if(update!=null){
				 video.setClickNum(update.getClickNum());
			 }
		}
		return video;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if(updateUrl!=null){
				UrlMeta responseToURL = CrawlHTML.responseToURL(updateUrl);
				if(responseToURL!=null){
					String clickNumstr=responseToURL.getHtml();
					if(clickNumstr!=null){
						clickNumstr = clickNumstr.replace("document.write('", "").replace("');", "").replace("\r\n", "").replace("ï»¿", "");
						Integer clickNum=0;
						try {
							clickNum=Integer.parseInt(clickNumstr);
						} catch (Exception e) {
							// TODO: handle exception
						}		
						meta.setClickNum(clickNum);
						return meta;
					}
				}
			}
		}	
		return null;
	}
	
	
	
}
